package model;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import database.MochilerosSQLiteHelper;

public class CategoriaDAO {
	Activity activity = null;
	
	public CategoriaDAO(Activity activity) {
		this.activity = activity;
	}
	
	public void insert(Categoria categoria){
		Integer idCategoria = calcularId();
		String nombre = categoria.getNombre();
		
		MochilerosSQLiteHelper mochilerosDBH = new MochilerosSQLiteHelper(activity, "DBMochileros", null, 3);
    	SQLiteDatabase db = mochilerosDBH.getWritableDatabase();
    	
		if (db != null) {
			db.execSQL("INSERT INTO Categoria (id_categoria, nombre)"
					+ " VALUES ("
					+ idCategoria
					+ ","
					+ "'"
					+ nombre
					+ "'"
					+ ","
					+ ")");
			db.close();
		}
	}
	
	public Integer calcularId(){
		MochilerosSQLiteHelper mochilerosDBH = new MochilerosSQLiteHelper(activity, "DBMochileros", null, 3);
    	SQLiteDatabase db = mochilerosDBH.getWritableDatabase();
		Cursor c = db.rawQuery("SELECT max(id_categoria) FROM Categoria", null);
		if (c.moveToFirst()) {
			return c.getInt(0)+1;
		}
		db.close();
		return null;
	}
	
	public List<Categoria> buscarPorExample(Categoria categoriaExample){
		MochilerosSQLiteHelper mochilerosDBH = new MochilerosSQLiteHelper(activity, "DBMochileros", null, 3);
    	SQLiteDatabase db = mochilerosDBH.getWritableDatabase();
    	Cursor c = null;
    	if(categoriaExample != null && categoriaExample.getIdCatergoria() != null && categoriaExample.getNombre() == null){
    		c = db.rawQuery("SELECT * FROM Categoria WHERE id_categoria="+categoriaExample.getIdCatergoria(), null);
    	}
    	else if(categoriaExample != null && categoriaExample.getIdCatergoria() == null && categoriaExample.getNombre() != null){
    		c = db.rawQuery("SELECT * FROM Categoria WHERE nombre='"+categoriaExample.getNombre()+"'", null);
    	}
    	else if(categoriaExample != null && categoriaExample.getIdCatergoria() != null && categoriaExample.getNombre() != null){
    		c = db.rawQuery("SELECT * FROM Categoria WHERE id_categoria="+categoriaExample.getIdCatergoria()+" AND nombre='"+categoriaExample.getNombre()+"'", null);
    	}
    	else if(categoriaExample ==null){
    		c = db.rawQuery("SELECT * FROM Categoria ORDER BY id_categoria DESC", null);
    	}

		if (c != null) {
			List<Categoria> listaCategorias = new ArrayList<Categoria>();
			if (c.moveToFirst()) {
				do {
					Categoria categoria = new Categoria();
					categoria.setIdCatergoria(c.getInt(0));
					categoria.setNombre(c.getString(1));
					listaCategorias.add(categoria);
					categoria = new Categoria();
				} while (c.moveToNext());
			}
			if (!listaCategorias.isEmpty()) {
				db.close();
				return listaCategorias;
			}
		}
		db.close();
		return null;
	}
}
